<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="计划年月">
          <el-date-picker
              v-model="searchParam.planYearMonth"
              type="month"
              placeholder="请输入年月"
              value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"><i-ep-search/>搜索</el-button>
          <el-button @click="reset"><i-ep-refresh/>重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button type="success" plain @click="openDialog()"><i-ep-plus />新增</el-button>
                   <el-button type="danger" plain :disabled="ids.length === 0" @click="handleTableDelete()"><i-ep-delete />删除</el-button>-->
        <el-button type="primary" @click="blackPieceImport">
          <template #icon><i-ep-upload/></template>导入
        </el-button>

      </template>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="年" prop="planYear" min-width="100" show-overflow-tooltip>
    </el-table-column>
        <el-table-column label="月" prop="planMonth" min-width="100" show-overflow-tooltip>
    </el-table-column>
        <el-table-column label="实际重量" prop="actualWeight" min-width="100" show-overflow-tooltip>
    </el-table-column>
        <el-table-column label="操作时间" prop="lastUpdateTime" min-width="160" show-overflow-tooltip align="center">
    </el-table-column>
        <el-table-column label="操作人" prop="lastUpdatedUserName" min-width="100" show-overflow-tooltip>
    </el-table-column>
        <!--<el-table-column fixed="right" label="操作" width="240">
        <template #default="scope">
          <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
          ><i-ep-search />
            查看
          </el-button>
          <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"><i-ep-edit />编辑</el-button>
          <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"><i-ep-delete />删除</el-button>
        </template>
      </el-table-column>-->
      </el-table>

      <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <mesblackpieceweightrecord-edit
        :visible="addDialog.visible"
        :title="addDialog.title"
        :data="addDialog.data"
        @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
        :is-readonly="addDialog.readvisible"
        @change-visible="changeVisible"
    />
    <ImportExcel ref="blackPieceImportRef"/>
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table
        ref="uploadErrorRef"
        :errorDataList="errorDataList"
        :promptDataList="promptDataList"
        :paramList="paramList"
        :listWorkOrder="listWorkOrder"
        @changelist="changelist"
    />
  </div>
</template>

<script setup lang="ts">
  import {useTable, useDownload, useDictionary} from "@/utils/useTable";
  import request from "@/utils/request";

  defineOptions({
    name: "MESMESBLACKPIECEWEIGHTRECORD",
    inheritAttrs: false,
  });

  // 请求参数
  const requestApi = "/mes/mesblackpieceweightrecord/queryByPage";

  // 是否需要分页
  const pagination = true;

  const initParam = {};

  // 初始化搜索参数数据
  const searchParamInit = {
    planYearMonth: "",
  };

  const deleteParam = {
    api: "/mes/mesblackpieceweightrecord/delete",
    data: {},
  };

  // 数据请求错误后处理
  function requestError() {
  }

  const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

  // 表格操作 Hooks
  const {
    tableData,
    pageable,
    searchParam,
    ids,
    getTableList,
    search,
    reset,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleTableDelete,
    loading,
  }: any = useTable(
      requestApi,
      initParam,
      searchParamInit,
      pagination,
      dataCallBack.value,
      requestError,
      deleteParam
  );

  onMounted(() => {
    getTableList();
  });

  const addDialog = reactive<DialogOption>({
    visible: false,
    readvisible: false,
    title: "",
    data: {},
  });

  // 查询详情
  async function getInfo(id: string) {
    request({
      url: `/mes/mesblackpieceweightrecord/get/${id}`,
      method: "get",
    }).then(data => {
      addDialog.data = data.data;
      addDialog.visible = true;
    }).catch(res => {
      console.log(res)
    });
  }

  /** 打开黑件重量记录表单弹窗 */
  function openDialog(roleObj?: Object) {
    if (roleObj) {
      addDialog.title = "修改黑件重量记录";
      getInfo(roleObj.id);
    } else {
      addDialog.title = "新增黑件重量记录";
      addDialog.visible = true;
    }
    addDialog.readvisible = false;
  }

  /** 打开黑件重量记录表单弹窗 详情 */
  function openDialogdetail(roleObj?: any) {
    addDialog.title = "黑件重量记录详情";
    getInfo(roleObj.id);
    addDialog.readvisible = true;
  }

  function changeVisible(value: boolean) {
    addDialog.visible = value;
    if (!value) {
      addDialog.data = {};
    }
  }


  // 导入excel
  const uploadApi = "/mes/mesblackpieceweightrecord/upload";
  const excelBox = ref(false);
  const uploadBtn = ref(false);
  const uploadFile = ref("");
  const fileName = ref("");

  function excelBoxOpen() {
    excelBox.value = true
  }

  function getfilepath(e: any) {
    const file = e.target.files[0];
    fileName.value = file.name;
    uploadFile.value = file;
    uploadBtn.value = false;
  }

  function upload() {
    if (!uploadFile.value) {
      ElMessage({
        type: "warning",
        message: "请选择文件！",
      });
      return;
    }

    let formdata = new FormData();
    formdata.append("file", uploadFile.value);
    let config = {headers: {"Content-Type": "multipart/form-data"}};
    request.post(uploadApi, formdata, config).then(res => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false
      uploadBtn.value = true
      search()
    }).catch(error => {
      console.log(error)
    })
  }

  async function deleteItem(id: any) {
    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const {data} = await request({
        url: `/mes/mesblackpieceweightrecord/deleteItem/${id}`,
        method: "post",
      });
      search();
    });
  }


  // 导入周数据
  const blackPieceImportRef = ref();
  const uploadErrorRef = ref();
  const errorDataList = ref([]);
  const promptDataList = ref([]);
  const listWorkOrder = ref([]);
  const paramList = ref({});

  async function blackPieceImportApiFunc(formdata: FormData, config: any) {
    await request
        .post("/mes/mesblackpieceweightrecord/upload", formdata, config)
        .then((res: any) => {
        });
  }

  const changelist = () => {
    search();
  };
  const blackPieceImport = () => {
    let newSearchParam = {...searchParam.value};
    let params = {
      title: "导入黑件重量数据",
      tempApi: "/mes/mesblackpieceweightrecord/exportTemp", //模板下载
      importApi: blackPieceImportApiFunc, // 导入
      getTableList, // 成功后回调
      isShowTemp: true, // 是否显示下载模板
      fileTypes: ".xlsx",
      searchParam: newSearchParam,
    };
    blackPieceImportRef.value.acceptParams(params);
  };
</script>
